<template>
  <div class="settings-container">
      <el-card class="settings-card">
        <template #header>
          <h2>应用设置</h2>
        </template>
        
        <el-form :model="settings" label-width="120px" class="settings-form">
          <el-form-item label="语音识别语言">
            <el-select v-model="settings.language" placeholder="选择语言">
              <el-option label="中文（简体）" value="zh-CN" />
              <el-option label="中文（繁体）" value="zh-TW" />
              <el-option label="英语（美国）" value="en-US" />
              <el-option label="英语（英国）" value="en-GB" />
              <el-option label="日语" value="ja-JP" />
              <el-option label="韩语" value="ko-KR" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="连续识别">
            <el-switch v-model="settings.continuous" />
            <span class="form-tip">开启后可以连续进行语音识别</span>
          </el-form-item>
          
          <el-form-item label="实时结果">
            <el-switch v-model="settings.interimResults" />
            <span class="form-tip">开启后可以实时显示识别结果</span>
          </el-form-item>
          
          <el-form-item label="最大备选结果">
            <el-input-number 
              v-model="settings.maxAlternatives" 
              :min="1" 
              :max="10" 
            />
            <span class="form-tip">设置返回的最大备选结果数量</span>
          </el-form-item>
          
          <el-form-item label="主题设置">
            <el-radio-group v-model="settings.theme">
              <el-radio label="light">浅色主题</el-radio>
              <el-radio label="dark">深色主题</el-radio>
              <el-radio label="auto">跟随系统</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="自动保存">
            <el-switch v-model="settings.autoSave" />
            <span class="form-tip">自动保存识别结果到本地存储</span>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveSettings">保存设置</el-button>
            <el-button @click="resetSettings">重置设置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card class="storage-card">
        <template #header>
          <h3>存储管理</h3>
        </template>
        
        <div class="storage-info">
          <p>已保存的识别记录：{{ savedRecords.length }} 条</p>
          <p>存储空间使用：{{ storageSize }}</p>
        </div>
        
        <div class="storage-actions">
          <el-button type="warning" @click="clearStorage">清空所有记录</el-button>
          <el-button type="info" @click="exportStorage">导出记录</el-button>
        </div>
      </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Settings {
  language: string
  continuous: boolean
  interimResults: boolean
  maxAlternatives: number
  theme: string
  autoSave: boolean
}

// 默认设置
const defaultSettings: Settings = {
  language: 'zh-CN',
  continuous: true,
  interimResults: true,
  maxAlternatives: 1,
  theme: 'light',
  autoSave: false
}

const settings = reactive<Settings>({ ...defaultSettings })
const savedRecords = ref<any[]>([])
const storageSize = ref('0 KB')

// 加载设置
const loadSettings = () => {
  const saved = localStorage.getItem('vue-sound-settings')
  if (saved) {
    Object.assign(settings, JSON.parse(saved))
  }
  
  // 加载保存的记录
  const records = localStorage.getItem('vue-sound-records')
  if (records) {
    savedRecords.value = JSON.parse(records)
  }
  
  // 计算存储大小
  calculateStorageSize()
}

// 保存设置
const saveSettings = () => {
  localStorage.setItem('vue-sound-settings', JSON.stringify(settings))
  ElMessage.success('设置已保存')
}

// 重置设置
const resetSettings = () => {
  Object.assign(settings, defaultSettings)
  ElMessage.info('设置已重置')
}

// 计算存储大小
const calculateStorageSize = () => {
  const records = localStorage.getItem('vue-sound-records')
  if (records) {
    const size = new Blob([records]).size
    if (size < 1024) {
      storageSize.value = `${size} B`
    } else if (size < 1024 * 1024) {
      storageSize.value = `${(size / 1024).toFixed(2)} KB`
    } else {
      storageSize.value = `${(size / (1024 * 1024)).toFixed(2)} MB`
    }
  } else {
    storageSize.value = '0 KB'
  }
}

// 清空存储
const clearStorage = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有保存的识别记录吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    localStorage.removeItem('vue-sound-records')
    savedRecords.value = []
    storageSize.value = '0 KB'
    ElMessage.success('存储已清空')
  } catch {
    // 用户取消
  }
}

// 导出存储
const exportStorage = () => {
  const records = localStorage.getItem('vue-sound-records')
  if (!records) {
    ElMessage.warning('没有可导出的记录')
    return
  }
  
  const blob = new Blob([records], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `vue-sound-records_${new Date().toISOString().split('T')[0]}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  ElMessage.success('记录已导出')
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 0 auto;
}

.settings-card {
  margin-bottom: 20px;
}

.settings-form {
  padding: 20px 0;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}

.storage-card {
  margin-top: 20px;
}

.storage-info {
  margin-bottom: 20px;
}

.storage-info p {
  margin: 5px 0;
  color: #666;
}

.storage-actions .el-button {
  margin-right: 10px;
}
</style>
